﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using YK.Component.Tools;

using NHibernate;
using NHibernate.Mapping.ByCode;


namespace YK.Test
{
    public class OralceDbManager
    {
       private  ISession session;// = new Configuration().Configure().BuildSessionFactory();  // 使用单例模式创建IsessionFactory

        private static  OralceDbManager _instance = null;

        private static readonly object SynObject = new object();

        //private ISessionFactory sessionFactory = null;
        public OralceDbManager()
        {
            try
            {
                var configuration = new NHibernate.Cfg.Configuration();
                configuration.Configure();

                var mapper = new ModelMapper();
                mapper.AddMappings(Assembly.Load("YK.Core.Data").GetTypes().
                        Where(m => m.Namespace == "YK.Core.Data.Repository.NHibernate.Mapping").ToList());
                //mapper.AddMapping(typeof(UserMapping));
                //mapper.AddMapping(typeof(RoleMapping));
                var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
                Debug.WriteLine(hbmMapping.AsString());
                Console.WriteLine(hbmMapping.AsString());

                configuration.AddDeserializedMapping(hbmMapping, "");

                session = configuration.BuildSessionFactory().OpenSession();
                //sessionFactory = new Configuration().Configure().BuildSessionFactory();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        //创建Session
        public static ISession NHSession
        {
            get
            {
                if (_instance == null)
                {
                    lock (SynObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new OralceDbManager();
                        }
                    }
                }
                return _instance.session;
            }
        }

    }
}
